import React, { useState, useEffect, useContext } from "react";
import getConfig from "next/config";
import Box from "./Box";
import Text from "./Text";
import TorrentList from "./TorrentList";
import { NotificationContext } from "./Notifications";
import LocaleContext from "../utils/LocaleContext";

const SimilarTorrents = ({ infoHash, token, count = 6 }) => {
  const [similarTorrents, setSimilarTorrents] = useState([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);

  const { addNotification } = useContext(NotificationContext);
  const { getLocaleString } = useContext(LocaleContext);

  const {
    publicRuntimeConfig: { SQ_API_URL, SQ_TORRENT_CATEGORIES },
  } = getConfig();

  // 调试: 组件挂载时打印 props
  useEffect(() => {
    console.log("SimilarTorrents mounted with props:", {
      infoHash,
      token: !!token,
      count,
    });
    console.log("SQ_API_URL:", SQ_API_URL);
  }, []);

  useEffect(() => {
    const fetchSimilarTorrents = async () => {
      console.log("fetchSimilarTorrents called with infoHash:", infoHash);

      if (!infoHash) {
        console.log("No infoHash provided, skipping fetch");
        setLoading(false);
        return;
      }

      try {
        setLoading(true);
        setError(null);

        const headers = {};
        if (token) {
          headers.Authorization = `Bearer ${token}`;
          console.log("Added Authorization header");
        }

        const url = `${SQ_API_URL}/recommendation/torrent/${infoHash}/similar?count=${count}`;
        console.log("Fetching similar torrents from:", url);
        console.log("Request headers:", headers);

        const response = await fetch(url, { headers });

        console.log("Response status:", response.status);
        console.log("Response ok:", response.ok);

        if (!response.ok) {
          throw new Error(
            `获取相似资源失败: ${response.status} ${response.statusText}`
          );
        }

        const data = await response.json();
        console.log("Response data:", data);
        console.log(
          "Recommendations count:",
          data.recommendations?.length || 0
        );

        // 获取完整的种子详情
        if (data.recommendations && data.recommendations.length > 0) {
          const detailedTorrents = await fetchTorrentDetails(
            data.recommendations
          );
          setSimilarTorrents(detailedTorrents);
        } else {
          setSimilarTorrents([]);
        }
      } catch (error) {
        console.error("获取相似资源失败:", error);
        setError(error.message);
        // 可选：显示错误通知
        addNotification(
          "error",
          getLocaleString("recommendations.similarError") || "获取相似资源失败"
        );
      } finally {
        setLoading(false);
        console.log("fetchSimilarTorrents completed");
      }
    };

    // 获取完整的种子详情
    const fetchTorrentDetails = async (recommendations) => {
      if (!recommendations || recommendations.length === 0) {
        return [];
      }

      try {
        const torrentsData = [];

        for (const rec of recommendations) {
          try {
            const torrentId = rec.torrentId;
            console.log("获取推荐种子详情:", torrentId);

            // 获取完整种子信息
            const response = await fetch(
              `${SQ_API_URL}/torrent/details/${torrentId}`,
              {
                headers: {
                  Authorization: `Bearer ${token}`,
                },
              }
            );

            if (response.ok) {
              const torrentData = await response.json();
              console.log(`获取到种子 ${torrentId} 详情，检查数据:`, {
                hasScore: !!torrentData.score,
                hasScoreStats: !!torrentData.scoreStats,
                commentsCount: torrentData.comments?.count,
              });

              // 确保种子包含必要字段
              const enhancedTorrent = {
                ...torrentData,
                recommendationScore: rec.score,
                recommendationReason: rec.reason,
                // 确保comments字段存在
                comments: torrentData.comments || { count: 0 },
              };

              torrentsData.push(enhancedTorrent);
            } else {
              console.warn(`获取种子 ${torrentId} 失败: ${response.status}`);
            }
          } catch (err) {
            console.error("获取种子详情出错:", err);
          }
        }

        console.log(`获取了 ${torrentsData.length} 个推荐种子的详细信息`);
        return torrentsData;
      } catch (error) {
        console.error("获取种子详情失败:", error);
        return [];
      }
    };

    fetchSimilarTorrents();
  }, [infoHash, token, count, SQ_API_URL]);

  // 调试: 状态变化时打印
  useEffect(() => {
    console.log("SimilarTorrents state changed:", {
      loading,
      similarTorrentsCount: similarTorrents.length,
      error,
      shouldRender: !(
        (loading && !similarTorrents.length) ||
        (!loading && !similarTorrents.length)
      ),
    });
  }, [loading, similarTorrents, error]);

  // 如果没有相似资源，不显示组件
  if (
    (loading && !similarTorrents.length) ||
    (!loading && !similarTorrents.length)
  ) {
    console.log("SimilarTorrents: Not rendering (no data)");
    return null;
  }

  console.log("SimilarTorrents: Rendering component");

  return (
    <Box mb={5}>
      <Text as="h2" mb={4}>
        {getLocaleString("recommendations.similar") || "相似资源"}
      </Text>
      {loading ? (
        <Text>{getLocaleString("common.loading") || "加载中..."}</Text>
      ) : error ? (
        <Text color="red">错误: {error}</Text>
      ) : (
        <TorrentList
          torrents={similarTorrents}
          categories={SQ_TORRENT_CATEGORIES}
          showRecommendationReason={true}
        />
      )}
    </Box>
  );
};

export default SimilarTorrents;
